package com.ny.until;

import com.ny.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfig jwtConfig;
    
    private static JwtInterceptor jwtInterceptor;
    
    @PostConstruct
    public void init() {
        jwtInterceptor = this;
        jwtInterceptor.jwtConfig = this.jwtConfig;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");

        // 如果没有token，则返回未授权错误
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"msg\":\"缺少访问令牌\",\"data\":null}");
            return false;
        }

        // 去掉Bearer前缀获取实际token
        token = token.substring(7);

        try {
            // 解析JWT token
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtInterceptor.jwtConfig.getSecret())
                    .parseClaimsJws(token)
                    .getBody();

            // 从token中获取用户ID，并放入request属性中供后续使用
            Integer userId = Integer.valueOf(claims.getSubject());
            request.setAttribute("userId", userId);

            // 验证通过，继续执行后续操作
            return true;
        } catch (Exception e) {
            // token无效或过期
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"msg\":\"令牌无效或已过期\",\"data\":null}");
            return false;
        }
    }
}